import { RbacRoleType } from '@/datatypes/rbacRole/data';
import type { RbacUserType } from '@/datatypes/rbacuser/data';
import { RbacUserStatusValueEnum } from '@/enums/auth';
import { useRoles } from '@/hooks/useRoles';
import UpdateForm from '@/pages/auth/rbacUser/components/UpdateForm';
import AddPermForm from '@/pages/tenant/oauthClientDetails/components/AddPermForm';
import { handleAdd, handleRemoveList, handleUpdate, page } from '@/services';
import { OauthClientDetailsPermissionUrl, rbacUserRolesUrl, rbacUserUrl } from '@/urls';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Drawer } from 'antd';
import React, { useRef, useState } from 'react';
import { default as RoleTags } from './components/RoleTags';

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<RbacUserType>();
  const [selectedRowsState, setSelectedRows] = useState<RbacUserType[]>([]);

  const roles = useRoles();


  // @ts-ignore
  const columns: ProColumns<RbacUserType>[] = [
    {
      title: '管理员ID',
      dataIndex: 'id',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '禁用',
          status: '0',
        },
        1: {
          text: '启用',
          status: '1',
        },
        2: {
          text: '离职',
          status: '2',
        },
      },
    },
    {
      title: '角色',
      dataIndex: 'roleIdString',
      hideInSearch: true,
      render: (text: any) => <RoleTags roleIdString={text} roles={roles} />,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      hideInSearch: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '姓名',
      dataIndex: 'realName',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,

      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<RbacUserType, API.PageParams>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(data) => page('auth/rbacUser/roles', data)}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemoveList(rbacUserUrl, selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建管理员"
        width="400px"
        open={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(rbacUserUrl, value as RbacUserType);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '用户名为必填项',
            },
          ]}
          width="md"
          name="username"
          label={'用户名'}
          placeholder={'请输入用户名'}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '密码为必填项',
            },
          ]}
          width="md"
          name="password"
          label={'密码'}
          placeholder={'请输入密码'}
        />
        <ProFormText width="md" name="mobile" label={'手机号'} placeholder={'请输入手机号'} />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '至少选择一个角色',
            },
          ]}
          width="md"
          name="roles"
          label={'角色'}
          mode="multiple"
          options={roles.map((role: RbacRoleType) => ({ label: role.name, value: role.id }))}
        />
        <ProFormSelect name="status" width="md" label={'状态'} valueEnum={RbacUserStatusValueEnum} />
        <ProFormTextArea width="md" name="remark" label={'备注'} placeholder={''} />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(rbacUserUrl, value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />


      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.username && (
          <ProDescriptions<RbacUserType>
            column={2}
            title={currentRow?.username}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.username,
            }}
            columns={columns as ProDescriptionsItemProps<RbacUserType>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
